package com.suxin.completablefuture;

import org.junit.Test;

import java.util.concurrent.*;

/**
 * @author Tang
 * @classname MainTest
 * @description [  ]
 * @date 2021/10/11 15:14
 */
public class MainTest {


    public static void main(String[] args) throws Exception{

        CompletableFuture<Object> completableFuture = new CompletableFuture<>();

        CompletableFuture<Object> future1 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("future1--是否是守护线程--->" + Thread.currentThread().isDaemon());
            completableFuture.complete("11"); // 结果只能手动设置一次
            return "hello !";
        });

        // 阻塞等待结果
        Object result = completableFuture.get();

        System.out.println("result--->" + result);

        System.out.println("main thread end");
    }

    private final ExecutorService executorService = Executors.newFixedThreadPool(2);

    @Test
    public void test01() throws Exception{
        CompletionService completionService = new ExecutorCompletionService(executorService);
        completionService.submit(new Callable() {
            @Override
            public Object call() throws Exception {
                TimeUnit.SECONDS.sleep(5);
                return "result...1";
            }
        });
        completionService.submit(new Callable() {
            @Override
            public Object call() throws Exception {
                TimeUnit.SECONDS.sleep(5);
                return "result...2";
            }
        });

        Future future = completionService.take();
        System.out.println(future.get());
        future = completionService.take();
        System.out.println(future.get());
    }

}